package com.bailan.foreat.controller;


import com.bailan.foreat.entity.Seller;
import com.bailan.foreat.service.SellerService;
import com.bailan.foreat.service.StoreService;
import com.bailan.foreat.utils.CookieUtils;
import com.bailan.foreat.utils.JwtUtils;
import com.google.code.kaptcha.Producer;
import com.bailan.foreat.utils.SellerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ste
 * @since 2023-02-21 07:50:43
 */
@Controller
@RequestMapping("/seller")
public class SellerController {

    @Autowired
    Producer producer;

    @Autowired
    SellerService sellerService;

    @Autowired
    StoreService storeService;

    @RequestMapping("/register")
    @ResponseBody
    public String register(String sellerName,String sellerPassword,String rePassword,String sellerImg){
        try{
            sellerService.register(sellerName,sellerPassword,rePassword,sellerImg);
        }catch (RuntimeException exception){
            exception.printStackTrace();
            return exception.getMessage();
        }

        return "ok";
    }

    @RequestMapping("/addCookie")
    @ResponseBody
    public String addCookie(String name, String value, HttpServletResponse response){

        //创建Cookie对象
        Cookie cookie = new Cookie(name,value);
        // domain + path  确定了cookie的生效范围
        //cookie.setDomain(""); //domain 域名   可以自己指定域名,也可以不写,不写的话默认就是当前网站的地址.
        cookie.setPath("/"); //在域名范围内的那些路径下是有效的   / 表示在当前网站下都有效
        cookie.setMaxAge(160);//设置cookie的有效期,单位秒
        cookie.setComment("测试cookie");

        response.addCookie(cookie);

        return "ok";
    }


    @RequestMapping("/queryCookie")
    @ResponseBody
    public String queryCookie(HttpServletRequest request){

        Cookie[] cookies = request.getCookies();
        for(int i=0;cookies!=null && i<cookies.length;i++){
            System.out.println(cookies[i]);
        }

        return "ok";
    }



    @RequestMapping("/updateCookie")
    @ResponseBody
    public String updateCookie(String name, String value, HttpServletResponse response){

        //更新cookie  重新写一遍

        //创建Cookie对象
        Cookie cookie = new Cookie(name,value);
        // domain + path  确定了cookie的生效范围
        //cookie.setDomain(""); //domain 域名   可以自己指定域名,也可以不写,不写的话默认就是当前网站的地址.
        cookie.setPath("/"); //在域名范围内的那些路径下是有效的   / 表示在当前网站下都有效
        cookie.setMaxAge(160);//设置cookie的有效期,单位秒   如果为0,就表示删除
        cookie.setComment("测试cookie");

        response.addCookie(cookie);

        return "ok";
    }



    @RequestMapping("/delCookie")
    @ResponseBody
    public String delCookie(String name, String value, HttpServletResponse response){

        //删除cookie  cookie.setMaxAge(0)

        //创建Cookie对象
        Cookie cookie = new Cookie(name,value);
        // domain + path  确定了cookie的生效范围
        //cookie.setDomain(""); //domain 域名   可以自己指定域名,也可以不写,不写的话默认就是当前网站的地址.
        cookie.setPath("/"); //在域名范围内的那些路径下是有效的   / 表示在当前网站下都有效
        cookie.setMaxAge(0);//设置cookie的有效期,单位秒   如果为0,就表示删除
        cookie.setComment("测试cookie");

        response.addCookie(cookie);

        return "ok";
    }


    @RequestMapping("getKaptchaImage")
    public void getKaptchaImage(HttpServletResponse response, HttpSession httpSession) throws IOException {
        //生成验证码
        String codeText = producer.createText();
//        codeText="0000"; //手动指定验证码,方便调试
        httpSession.setAttribute("kaptchaCode",codeText);

        BufferedImage codeImage = producer.createImage(codeText);

        response.setContentType("image/png");
        ImageIO.write(codeImage,"png",response.getOutputStream());

    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String sellerName, String sellerPassword, HttpServletResponse response, HttpSession httpSession, String code, Model model){
        //校验验证码
        String kaptchaCode = (String)httpSession.getAttribute("kaptchaCode");
        if (StringUtils.isEmpty(code) || !code.equalsIgnoreCase(kaptchaCode)){
            return "验证码错误";
        }

        try {
            sellerService.login(sellerName,sellerPassword);
            String token = JwtUtils.createToken(sellerName, 15);
            CookieUtils.setUserToken2Cookie(response,token);
        }catch (RuntimeException exception){
            exception.printStackTrace();
            return exception.getMessage();
        }
        return "ok";
    }


    @RequestMapping("currentUserName")
    @ResponseBody
    public String currentUserName(HttpServletRequest request){
        //从cookie中拿到userToken
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        //然后从userToken中解析出用户名
        String accountFromToken = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        return accountFromToken;
    }

    @RequestMapping("currentSeller")
    @ResponseBody
    public Seller currentSeller(HttpServletRequest request) {
        Seller currentSeller = SellerUtils.getCurrentSeller(request);
        return currentSeller;
    }

    @RequestMapping("/updateByImg")
//    @ResponseBody
    public String updateByImg(HttpServletRequest request, MultipartFile source){
        Seller currentSeller = SellerUtils.getCurrentSeller(request);
        if (source != null) {
            String originalFilename = source.getOriginalFilename();
            if (!originalFilename.equals("")) {
                String fileName = "http://localhost:10002/imgs/head/" + originalFilename;

                //保存图片的路径到数据
                //设置图片路径到实体对象
                currentSeller.setSellerImg(fileName);
            }
        }else {
            currentSeller.setSellerImg(currentSeller.getSellerImg());
        }
        sellerService.updateById(currentSeller);
        return "center";
    }


    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpServletResponse response){
        CookieUtils.deleteUserTokenFromCookie(response);
        return "ok";
    }

    @RequestMapping("redirectLoginHtml")
    public String redirectLoginHtml(){
        return "login";
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public String changePassword(String sellerOldPassword,String sellerPassword,String rePassword,HttpServletRequest request){
        try{
            String currentSellerName = currentUserName(request);
            sellerService.changePassword(sellerOldPassword,sellerPassword,rePassword,currentSellerName);
        }catch (RuntimeException exception){
            exception.printStackTrace();
            return exception.getMessage();
        }

        return "ok";
    }
}

